<template>
  <el-dialog
    v-model="visible"
    :title="$t('product.select')"
    :before-close="close"
    append-to-body
    top="5vh"
    :close-on-click-modal="false"
    class="components-single-prods-select"
  >
    <el-form
      :inline="true"
      :model="dataForm"
      class="demo-form-inline"
      @submit.prevent
    >
      <el-form-item :label="$t('product.itemName')">
        <el-input
          v-model="prodName"
          :placeholder="$t('product.itemName')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('product.singleProductBar')">
        <el-input
          v-model="barCode"
          :placeholder="$t('product.singleProductBar')"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('marketing.subHeadings')">
        <el-cascader
          v-model="selectedCategory"
          expand-trigger="hover"
          :options="categoryList"
          :props="categoryTreeProps"
          :clearable="true"
          @change="handleChange"
        />
      </el-form-item>
      <div class="btn-row">
        <div
          class="default-btn primary-btn"
          @click="searchProd"
        >
          {{ $t("order.query") }}
        </div>
        <div
          class="default-btn"
          @click="clean"
        >
          {{ $t("temp.setNull") }}
        </div>
      </div>
    </el-form>
    <div class="prods-select-body">
      <el-table
        ref="prodTableRef"
        v-loading="dataListLoading"
        :data="dataList"
        header-cell-class-name="table-header"
        row-class-name="table-row"
        style="width: 100%;"
        @selection-change="selectChangeHandle"
      >
        <el-table-column
          v-if="props.isSingle"
          width="50"
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <div>
              <el-radio
                v-model="singleSelectProdId"
                :label="scope.row.retailProdId"
                @change="getSelectProdRow(scope.row)"
              >
&nbsp;
              </el-radio>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="!props.isSingle"
          type="selection"
          header-align="center"
          align="center"
          width="50"
        />
        <el-table-column
          align="center"
          width="140"
          :label="$t('product.singleProdPic')"
        >
          <template #default="scope">
            <ImgShow
              :src="scope.row.pic"
              width="100"
              height="100"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="name"
          header-align="center"
          align="center"
          :label="$t('product.itemName')"
        />
        <el-table-column
          prop="spec"
          header-align="center"
          align="center"
          :label="$t('product.singleProdSpe')"
        >
          <template #default="scope">
            <div>{{ scope.row.spec || '-' }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="costPrice"
          header-align="center"
          align="center"
          :label="$t('product.singleProd')"
        />
        <el-table-column
          prop="stocks"
          header-align="center"
          align="center"
          :label="$t('product.singleProdInve')"
        />
        <el-table-column
          prop="barCode"
          header-align="center"
          align="center"
          :label="$t('product.singleProductBar')"
        />
        <el-table-column
          prop="categoryName"
          header-align="center"
          align="center"
          :label="$t('product.singleProdClas')"
        >
          <template #default="scope">
            <div>{{ scope.row.categoryName || '-' }}</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-box">
      <el-pagination
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        @update:page-size="onPageSizeChange"
        @update:current-page="onPageChange"
      />
    </div>
    <template #footer>
      <span>
        <span
          class="default-btn"
          @click="close"
        >{{ $t("crud.filter.cancelBtn") }}</span>
        <span
          class="default-btn primary-btn"
          @click="submitProds()"
        >{{ $t("crud.filter.submitBtn") }}</span>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { treeDataTranslate, idList } from '@/utils'
const emit = defineEmits(['refreshSelectSingleProds'])
const dataForm = ref({
  product: ''
})
const page = ref({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const categoryTreeProps = {
  value: 'categoryId',
  label: 'categoryName'
}
const props = defineProps({
  isSingle: {
    default: false,
    type: Boolean
  },
  dataUrl: {
    default: '/shop/retailProd/page',
    type: String
  }
})

onActivated(() => {
  getDataList()
})
const visible = ref(false)
const close = () => {
  clean()
  visible.value = false
}
// 获取数据列表
const singleSelectProdId = ref(0)
const selectProds = ref([])
const dataListLoading = ref(false)
const dataListSelections = ref([])
let oriSelectData = [] // 选择的原来的数据
const init = (isSelectProds) => {
  singleSelectProdId.value = 0
  selectProds.value = isSelectProds
  visible.value = true
  dataListLoading.value = true
  if (selectProds.value) {
    selectProds.value.forEach(row => {
      dataListSelections.value.push(row)
      oriSelectData.push(row)
    })
  }
  getDataList()
  getCategoryList()
}
const categoryList = ref([])

const getCategoryList = () => {
  http({
    url: http.adornUrl('/prod/category/listCategory'),
    method: 'get',
    params: http.adornParams({
      status: 1
    })
  }).then(({ data }) => {
    categoryList.value = treeDataTranslate(data, 'categoryId', 'parentId')
  })
}
const dataList = ref([])
const prodName = ref('')
const barCode = ref('')
let shopCategoryId = null
const prodTableRef = ref(null)
const getDataList = () => {
  http({
    url: http.adornUrl(props.dataUrl),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: page.value.currentPage,
          size: page.value.pageSize,
          name: prodName.value || null,
          categoryId: shopCategoryId || null,
          barCode: barCode.value || null
        }
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.value.total = data.total
    dataListLoading.value = false
    if (selectProds.value) {
      nextTick(() => {
        selectProds.value.forEach(row => {
          const index = dataList.value.findIndex((prodItem) => prodItem.retailProdId === row.retailProdId)
          prodTableRef.value.toggleRowSelection(dataList.value[index])
        })
      })
    }
  })
}
// 每页数
const onPageSizeChange = (val) => {
  page.value.pageSize = val
  page.value.currentPage = 1
  getDataList()
}
// 当前页
const onPageChange = (val) => {
  page.value.currentPage = val
  getDataList()
}
// 单选商品事件
const getSelectProdRow = (row) => {
  dataListSelections.value = [row]
}
// 多选点击事件
const selectChangeHandle = (selection) => {
  dataList.value.forEach((tableItem) => {
    const selectedProdIndex = selection.findIndex((selectedProd) => {
      if (!selectedProd) {
        return false
      }
      return selectedProd.retailProdId === tableItem.retailProdId
    })
    const dataSelectedProdIndex = dataListSelections.value.findIndex((dataSelectedProd) => dataSelectedProd.retailProdId === tableItem.retailProdId)
    if (selectedProdIndex > -1 && dataSelectedProdIndex === -1) {
      dataListSelections.value.push(tableItem)
    } else if (selectedProdIndex === -1 && dataSelectedProdIndex > -1) {
      dataListSelections.value.splice(dataSelectedProdIndex, 1)
    }
  })
}
/**
 * 获取分类id
 */
const handleChange = (val) => {
  shopCategoryId = val[val.length - 1]
}
/**
 * 根据条件搜索商品
 */
const searchProd = () => {
  page.value.currentPage = 1
  getDataList()
}
/**
 * 清空搜索条件
 */
const selectedCategory = ref([])
const clean = () => {
  prodName.value = ''
  barCode.value = ''
  shopCategoryId = null
  selectedCategory.value = idList(categoryList.value, shopCategoryId, 'categoryId', 'children').reverse()
}
// 确定事件
const submitProds = () => {
  const prods = []
  dataListSelections.value.forEach(item => {
    const prodIndex = prods.findIndex((prod) => prod.retailProdId === item.retailProdId)
    if (oriSelectData.length) {
      const oriProd = oriSelectData.find((oriItem) => oriItem.retailProdId === item.retailProdId)
      if (oriProd) {
        item.retailNums = oriProd.retailNums
        item.total = oriProd.total
      } else {
        item.retailNums = 0
        item.total = 0
      }
    } else {
      item.retailNums = 0
      item.total = 0
    }
    if (prodIndex === -1) {
      prods.push(
        {
          retailProdId: item.retailProdId,
          name: item.name,
          pic: item.pic,
          barCode: item.barCode,
          stocks: item.stocks,
          spec: item.spec,
          costPrice: item.costPrice,
          retailNums: item.retailNums,
          total: item.total
        }
      )
    }
  })
  emit('refreshSelectSingleProds', prods)
  dataListSelections.value = []
  oriSelectData = []
  visible.value = false
}
defineExpose({ init })
</script>
<style lang="scss" scoped>
.components-single-prods-select{
  .prods-select-body {
  max-height: 520px;
  overflow: auto;
}
  .btn-row {
    margin-bottom: 15px;
  }
  div :deep(.el-pagination) {
    display: flex;
    justify-content: flex-end;
  }
  .pagination-box{
    padding-top: 20px;
    text-align: right;
    display: flex;
    justify-content: flex-end;
  }
}

</style>
